package com.cet.programmercarl.algorithmperformancanalysis.字符串;

/**
 * @program: algorithm
 * @description: 字符串反转2
 * @author: 陈恩涛
 * @create: 2022-03-19 10:46
 **/
public class LC541 {

    /**
     * s字符串中对字符进行计数，每至2k则将前k个字符串反转
     * 剩余字符串少于k个，则全部反转
     * 剩余字符串大于等于k小于2k则反转前k个
     * @param s
     * @param k
     * @return
     */
    public static String reverseStr(String s, int k) {
        StringBuilder result = new StringBuilder();
        int index = 0;
        int length = s.length();
        while (index < length) {
            StringBuilder temp = new StringBuilder();
            int firstK = index + k > length ? length : index + k;
            int secondk = index + 2 * k > length ? length : index + 2 * k;
            temp.append(s.substring(index,firstK));
            temp = temp.reverse();
            if (secondk > firstK) {
                temp.append(s.substring(firstK, secondk));
            }
            result.append(temp);
            index += 2 * k;
        }
        return result.toString();
    }
}
